<template>
  <el-card class="list-card">
    <template #header>
      <div class="card-header">
        <span>教师志愿选择</span>
      </div>
    </template>

    <div class="card-body">
      <!-- 筛选表单 -->
      <el-form :inline="true" :model="queryParams" class="search-container" label-width="auto" style="margin-bottom: 0">
        <el-form-item label="专业分组" prop="groupId">
          <el-select v-model="queryParams.groupId" placeholder="请选择专业分组" clearable filterable style="width: 200px" @change="handleGroupChange">
            <el-option v-for="group in majorGroupOptions" :key="group.groupId" :label="`${group.gradeName} - ${group.groupName}`" :value="group.groupId" />
          </el-select>
        </el-form-item>
        <el-form-item label="毕设名称">
          <el-input v-model="queryParams.teamName" placeholder="请输入毕设名称" clearable style="width: 200px" :disabled="!queryParams.groupId" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="学号">
          <el-input v-model="queryParams.stuId" placeholder="请输入学号" clearable style="width: 200px" :disabled="!queryParams.groupId" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="学生姓名">
          <el-input v-model="queryParams.studentName" placeholder="请输入学生姓名" clearable style="width: 200px" :disabled="!queryParams.groupId" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="是否选你志愿">
         <el-select v-model="queryParams.isSelected" placeholder="请选择是否选你志愿" clearable style="width: 200px" :disabled="!queryParams.groupId">
          <el-option label="是" value="1" />
          <el-option label="否" value="0" />
        </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery" :disabled="!queryParams.groupId">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 提示信息 -->
      <el-alert v-if="!queryParams.groupId" title="请先选择专业分组，然后查看队伍列表" type="info" :closable="false" style="margin-bottom: 16px" />

      <!-- 队伍列表 -->
      <div v-else class="table-container">
        <el-table v-loading="loading" :data="teamList" border row-key="teamId" height="100%">
          <el-table-column label="毕设名称" align="center" prop="teamName" show-overflow-tooltip />
          <el-table-column label="队长" align="center" width="120">
            <template #default="{ row }">
              {{ getLeaderName(row) }}
            </template>
          </el-table-column>
          <el-table-column label="成员" align="center" width="100">
            <template #default="{ row }">
              <el-button link type="primary" size="small" @click="handleViewMembers(row)">查看</el-button>
            </template>
          </el-table-column>
          <el-table-column label="志愿状态" align="center" width="120">
            <template #default="{ row }">
              <el-tag v-if="isSelected(row.teamId)" type="success" size="small">已选择</el-tag>
              <el-tag v-else type="info" size="small">未选择</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="毕设简介" align="center" width="120">
            <template #default="{ row }">
              <el-button link type="primary" size="small" @click="handleViewSummary(row)">查看</el-button>
            </template>
          </el-table-column>
          <el-table-column label="是否选你志愿" align="center" width="120">
            <template #default="{ row }">
              <el-tag v-if="row.teamTeachers?.some((tt) => tt.teacherId === props.teacherId)" type="success" size="small">是</el-tag>
              <el-tag v-else type="danger" size="small">否</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="120" fixed="right">
            <template #default="{ row }">
              <el-button v-if="!isSelected(row.teamId)" link type="primary" size="small" @click="handleSelect(row)" :disabled="isSelectDisabled">选择</el-button>
              <el-button v-else link type="danger" size="small" @click="handleUnselect(row.teamId)">取消</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <pagination
        v-if="queryParams.groupId"
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :page-sizes="[20, 30, 50]"
        @pagination="getTeamList"
      />
    </div>

    <!-- 成员查看弹窗 -->
    <TeamMemberDialog ref="memberDialogRef" />

    <!-- 简介查看弹窗 -->
    <TeamSummaryDialog ref="summaryDialogRef" />
  </el-card>
</template>

<script setup>
import { ref, computed, watch, getCurrentInstance } from 'vue'
import { getGradeTree } from '@/api/grade'
import { listByGradeAndTeacher } from '@/api/group'
import { listTeam } from '@/api/team'
import TeamMemberDialog from './TeamMemberDialog.vue'
import TeamSummaryDialog from './TeamSummaryDialog.vue'

const props = defineProps({
  selectedTeams: {
    type: Array,
    default: () => []
  },
  deptId: {
    type: Number,
    required: true
  },
  teacherId: {
    type: Number,
    required: true
  },
  maxVolunteer: {
    type: Number,
    default: 3
  }
})

const emit = defineEmits(['select-team', 'unselect-team', 'group-change'])
const { proxy } = getCurrentInstance()

// 数据
const loading = ref(false)
const teamList = ref([])
const total = ref(0)
const majorGroupOptions = ref([])

// 弹窗引用
const memberDialogRef = ref(null)
const summaryDialogRef = ref(null)

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 20,
  groupId: null,
  teamName: null,
  stuId: null,
  studentName: null,
  isSelected: null
})

// 获取专业分组列表（年级 + 分组组合）
const getMajorGroupList = async () => {
  try {
    const res = await getGradeTree()
    if (res && res.data) {
      // 找到当前院系的年级列表
      const gradeList = res.data.find((dept) => dept.deptId == props.deptId)?.children || []

      // 为每个年级获取分组，并构建组合选项
      const allGroupPromises = gradeList.map(async (grade) => {
        try {
          const groupRes = await listByGradeAndTeacher(grade.gradeId, props.teacherId)
          if (groupRes && groupRes.data) {
            // 为每个分组添加年级名称
            return (groupRes.data || []).map(group => ({
              ...group,
              gradeName: grade.gradeName,
              gradeId: grade.gradeId
            }))
          }
          return []
        } catch (error) {
          console.error(`获取年级 ${grade.gradeName} 的分组列表失败:`, error)
          return []
        }
      })

      // 等待所有请求完成并合并结果
      const allGroups = await Promise.all(allGroupPromises)
      majorGroupOptions.value = allGroups.flat()
    }
  } catch (error) {
    console.error('获取专业分组列表失败:', error)
  }
}

// 分组改变
const handleGroupChange = () => {
  queryParams.value.pageNum = 1

  // 找到当前选中的分组对象（从专业分组列表中查找）
  const selectedGroup = majorGroupOptions.value.find((g) => g.groupId === queryParams.value.groupId)

  // 通知父组件分组已变化（包含分组的完整信息）
  emit('group-change', selectedGroup || null)

  if (queryParams.value.groupId) {
    getTeamList()
  } else {
    teamList.value = []
    total.value = 0
  }
}

// 获取队伍列表
const getTeamList = async () => {
  if (!queryParams.value.groupId) return
    queryParams.value.teacherId = props.teacherId
  loading.value = true
  try {
    const res = await listTeam(queryParams.value)
    if (res && res.data) {
      teamList.value = res.data.rows || []
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('获取队伍列表失败:', error)
    proxy.$modal.msgError('获取队伍列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getTeamList()
}

// 重置
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 20,
    groupId: null,
    teamName: null,
    stuId: null,
    studentName: null,
    isSelected: null
  }
  teamList.value = []
  total.value = 0
}

// 判断是否已选择
const isSelected = (teamId) => {
  return props.selectedTeams.some((t) => t.teamId === teamId)
}

// 判断是否可以继续选择
const isSelectDisabled = computed(() => {
  return props.selectedTeams.length >= props.maxVolunteer
})

// 获取队长姓名
const getLeaderName = (team) => {
  const leader = team.studentTeams?.find((st) => st.isLeader === '1')
  return leader?.student?.user?.nickName || '未知'
}

// 选择队伍
const handleSelect = (team) => {
  if (props.selectedTeams.length >= props.maxVolunteer) {
    proxy.$modal.msgWarning(`最多只能选择${props.maxVolunteer}个志愿`)
    return
  }
  emit('select-team', team)
}

// 取消选择
const handleUnselect = (teamId) => {
  emit('unselect-team', teamId)
}

// 查看成员
const handleViewMembers = (team) => {
  if (memberDialogRef.value) {
    memberDialogRef.value.openDialog(team.studentTeams || [])
  }
}

// 查看简介
const handleViewSummary = (team) => {
  if (summaryDialogRef.value) {
    summaryDialogRef.value.openDialog(team)
  }
}

// 监听 deptId 变化，当有值时才加载专业分组列表
watch(
  () => props.deptId,
  (newDeptId) => {
    if (newDeptId) {
      console.log('deptId 已加载:', newDeptId)
      getMajorGroupList()
    }
  },
  { immediate: true }
)

// 暴露方法给父组件
defineExpose({
  resetQuery
})
</script>

<style scoped lang="scss">
.list-card {
  height: 100%;
  display: flex;
  flex-direction: column;

  :deep(.el-card__body) {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
}

.card-header {
    font-size: 24px;
  font-weight: 600;
  color: var(--el-color-primary);
}

.card-body {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.search-container {
  margin-bottom: 16px;
  padding: 12px;
  border-radius: 4px;
}

.table-container {
  flex: 1;
  overflow: hidden;
  margin-bottom: 16px;
}
</style>
